﻿/*

The MIT License (MIT)

Copyright (c) 2013, Must Not Sleep LLC

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

 
 */

 /**
 * restlessEngine 
 * @version    0.7
 * @author    Jordan Laine
 */
 
package restless.core {
	
	import com.greensock.TimelineMax;
	import flash.display.MovieClip;
    import flash.display.Sprite;
	import restless.core.gameObjs.RLEBlitMC;
	import restless.core.interfaces.I2d;
	import restless.core.managers.RLEGraphicsManager;
	import restless.core.managers.RLEXMLManager;
	import restless.menu.LoadingScreen;
	import restless.restlessAssets.splash.mns.MNSSplash;
    import restless.restlessAssets.splash.restless.RestlessSplash;
	import restless.utilities.Benchmark;

	
	import restless.core.managers.RLESoundManager;
	import restless.core.managers.RLEColisionManager;
	import restless.core.managers.RLEKeyboardManager;
	import restless.core.managers.RLEPowerupManager;
	import restless.core.managers.RLEScreenManager;
	import restless.core.managers.RLEMouseManager;
	import restless.core.managers.RLELevelManager;
	import restless.core.managers.RLETextManager;
	import restless.core.managers.RLETweenManager;
	import restless.core.managers.RLETimerManager;
	import restless.core.managers.RLEStatManager;
	
	import flash.display.DisplayObject;
	import flash.display.DisplayObjectContainer;
	import flash.display.Sprite;
	import flash.display.Stage;
	import flash.events.Event;
	import flash.events.GameInputEvent;
	import flash.events.MouseEvent;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
	
	import restless.utilities.console.C;
	import restless.utilities.numeric.RLENumberUtils;
	
	import restless.core.interfaces.ICreateTimers;
	import restless.core.interfaces.ILevel;
	import restless.core.interfaces.IMapList;
	import restless.core.interfaces.IScore;
	import restless.core.interfaces.IStage;
	import restless.core.interfaces.ITimer;
	import restless.core.interfaces.IUR;
	
	public class RestlessEngine extends MovieClip implements ICreateTimers, IStage {
		public static var instance:RestlessEngine;
		
		protected var game:RLELevel;
		protected var loadingScreen:LoadingScreen;
		
		public var splash:RLEBlitMC;		
		protected var _bkgColor:uint = 0xCCAA4400;
		
		private var _sID:String;
		private var _nID:Number;
		private var lock:Boolean = false;
		
		public var systemFunction:Function;
		public var currentSystemState:String;
		public var nextSystemState:String;
		public var lastSystemState:String;
		
		private	var	tempNum:int;
		private	var	tempObj:IUR;
		private	var	i:int;
		
		private var bPause:Boolean = false;
		
		private var nUpdate:int;
		private var vUpdate:Vector.<IUR>;
		private var bUpdate:Boolean = false;
		
		private var sNextState:String;
		private var bChangeState:Boolean;
		
		private var vCachedStorageStrings:Vector.<String>;
		private var vCachedStorage:Vector.<IUR>;

		public var timeLine:TimelineMax;
		public var RE:RestlessEngine;
		public var mark:Benchmark;
		
		public var levelM:RLELevelManager;
		public var colM:RLEColisionManager;
		
		public var screenM:RLEScreenManager;
		public var keyM:RLEKeyboardManager;
		public var mouseM:RLEMouseManager;
		public var timerM:RLETimerManager;
		public var powerM:RLEPowerupManager;
		public var statM:RLEStatManager;
		public var gfxM:RLEGraphicsManager;
		public var soundM:RLESoundManager;
		public var tweenM:RLETweenManager;
		public var textM:RLETextManager;
		public var xmlM:RLEXMLManager;
		
		private var _frameRate:int = 30;
		protected var nLevel:int = 0;
		
		protected var bConsole:Boolean = false;
		protected var bProfile:Boolean = false;
		protected var vTimers:Vector.<RLETickTimer> = new Vector.<RLETickTimer>;
		
		protected var timer:ITimer;
		
		private var _urlsAllowed:Array;
		
		protected var _worldWidth:int;
		protected var _worldHeight:int;
		protected var stageWidth:int;
		protected var stageHeight:int;
		protected var vLevels:Vector.<Class> = new <Class>[null];
		protected var vLevelData:Vector.<IScore> = new <IScore>[null];
		
		public function RestlessEngine() {
			instance = this;
			
			if (stage) {
				trace("Stage is ready!");
				addedToStage();
			} else  {
				addEventListener(Event.ADDED_TO_STAGE, addedToStage, false, 0, true);
			}
		}
		
		public function addedToStage(e:Event = null):void {
			this.mouseChildren = true;
			stage.align = StageAlign.TOP_LEFT;
			stage.scaleMode = StageScaleMode.NO_SCALE;
			//stage.stageHeight = _worldHeight;
			//stage.stageWidth = _worldWidth;
			init();
		}
		
		protected function init():void {
			if (lock) { return; }
			
			timeLine = new TimelineMax( { useFrames:true, autoRemoveChildren:true, onUpdate:UpdateRender, repeat:-1 } );
			vUpdate = new Vector.<IUR>;
				
			vCachedStorage = new Vector.<IUR>;
			vCachedStorageStrings = new Vector.<String>;
			statM = new RLEStatManager(_sID);
			soundM = new RLESoundManager();
			levelM = new RLELevelManager();
			colM = new RLEColisionManager();
			mouseM = new RLEMouseManager();
			screenM = new RLEScreenManager();
			keyM = new RLEKeyboardManager();
			
			timerM = new RLETimerManager();
			powerM = new RLEPowerupManager();
			
			gfxM = new RLEGraphicsManager();
			
			tweenM = new RLETweenManager(timeLine);
			textM = new RLETextManager();
			xmlM = new RLEXMLManager();
			
			textM.addFont(FONTRestlessEngine, textM.DEFAULT_FONT);
			textM.addTextFormat(textM.DEFAULT_FORMAT, textM.DEFAULT_FONT, RLENumberUtils.colorsToRGB(35, 35, 35));  
			statM.updateLocalObj();
		}
		
		private function UpdateRender():void {
			
			i = vUpdate.length-1;
			for(i; i > -1; i--) {
				tempObj = vUpdate[i];
				tempObj.update();
			}
			
			if (bChangeState) {
				bChangeState = false;
				switchSystemState(sNextState);
				return;
			}
			
			screenM.update();
			
			if (colM.updating) {
				//mark.start("Colide ");
				colM.update();
				//trace( mark.stopText() );
			}
			
			screenM.render();	
		}
		
		public function addArrayToUpdate(vArray:Vector.<IUR>):void {
			vUpdate = vUpdate.concat(vArray);
		}
		
		public function addToUpdate(asset:IUR):void {
			var num:int = vUpdate.indexOf(asset);
			if(num < 0) {
				vUpdate.push(asset);
				nUpdate++;
			}
		}
		
		public function removeFromUpdate(asset:IUR):void {
			var num:int = vUpdate.indexOf(asset);
			if (num > -1) {
				vUpdate.splice(num, 1);
				if (bUpdate) { nUpdate--; }
			}
		}
		
		public function set pause(bool:Boolean):void {
			if (bool == bPause) { return; }
			bPause = bool;
			
			if (bPause) {
				cacheUpdateObjs();
			} else {
				unCacheUpdateObjs();
			}
			
			if (keyM) {
				keyM.pause = bPause;
			}
		}
		
		protected function cacheUpdateObjs():void {
			vCachedStorage.length = 0;
			vCachedStorage.concat(vUpdate);
		}
		
		protected function unCacheUpdateObjs():void {
			vUpdate.length = 0;
			vUpdate.concat(vCachedStorage);
		}
		
		protected function sitelock():void {
			if (_urlsAllowed != null) {
				lock = true;
				this.alpha = 0;
				for (i = _urlsAllowed.lentght-1; i > -1; i-- ) {
					//trace("URLs " + urlsAllowed[i] + " domain " + domain());
					if (urlsAllowed[i] == domain) {
						lock = false;
						this.alpha = 1;
					}
				}
			}
		}
		
		public function domain():String {
			var currentDomain:String = this.loaderInfo.url.split("/")[2];
			var fqdn:Array = currentDomain.split(".");
			var rdi:int = 1;
			var tli:int = 2; 
			if (fqdn.length == 2) {
				rdi--;
				tli--;
			}
			return fqdn[rdi] + "." + fqdn[tli];
		}
		
		protected function RLE_Splash():void {
			loadingScreen.dispose();
			mouseM.addClickListeners();
			nextSystemState = RLEStates.STATE_SYSTEM_RLE_SPLASH_OUT;
			splash = new RestlessSplash();
		}
		
		protected function RLE_SplashOut():void {
			splash.dispose();
			splash = null;
			gfxM.removeGFXByName("restlessGfx");
			switchSystemState(RLEStates.STATE_SYSTEM_MNS_SPLASH);
		}
		
		protected function MNS_Splash():void {
			nextSystemState = RLEStates.STATE_SYSTEM_MNS_SPLASH_OUT;
			splash = new MNSSplash();
		}
		
		protected function MNS_SplashOut():void {
			splash.dispose();
			splash = null;
			systemPreload();
			gfxM.removeGFXByName("mnsSplash");
			switchSystemState(RLEStates.STATE_SYSTEM_MENU_IN);
		}
		
		protected function systemOptions():void {
			
		}
		
		protected function systemTitle():void {
			
		}
		
		protected function systemNewGame():void {
			
		}
		
		protected function systemInstructions():void {
			
		}
		
		protected function systemMenuIn():void {
			switchSystemState(RLEStates.STATE_SYSTEM_MENU);
		}
		
		protected function systemMenu():void {
			
		}
		
		protected function systemMenuOut():void {
			
		}
		
		protected function systemLevelIn():void {
		
		}
		
		protected function systemNewLevel():void {
		
		}
		
		protected function systemLevelOut():void {
			
		}
		
		protected function systemPauseIn():void {
		
		}
		
		protected function systemPause():void {
			
		}
		
		protected function systemPauseOut():void {
			
		}
		
		protected function systemPreload():void {
			levelM.load(vLevels, vLevelData);
		}
		
		protected function systemLoad():void {
			gfxM.startParse();
		}
		
		protected function systemLoadFinish():void {
			
		}
		
		protected function systemGameStart():void {
			
		}
		
		protected function systemGameOver():void {
			
		}
		
		protected function systemGamePlay():void {
			
		}
		
		protected function newLevel():void {
			
		}
		
		public function dispose():void {
			
		}
		
		public function set sID(id:String):void {
			_sID = id;
		}
		
		public function get sID():String {
			return _sID;
		}
		
		public function set nID(num:Number):void {
			_nID = num;
		}
		
		public function get nID():Number{
			return _nID;
		}
		
		public function addConsole(layer:DisplayObjectContainer):void {
			if (bConsole == true) {
				C.remove();
			}
			
			if (layer != null) {
				C.start(layer);
			} else {
				C.start(this);	
			}
			C.fpsMonitor = true;
			C.memoryMonitor = true;
			C.alwaysOnTop = true;
			
		}
		
		public function switchSystemState(stateval:String):void {
			lastSystemState = currentSystemState;
			currentSystemState = stateval;
			//trace("Switching System State to " + currentSystemState);
			//trace("currentSystemState = " + currentSystemState)
			switch(stateval) {
					
				case RLEStates.STATE_SYSTEM_MNS_SPLASH:
					systemFunction = MNS_Splash;
					break;
					
				case RLEStates.STATE_SYSTEM_MNS_SPLASH_OUT:
					systemFunction = MNS_SplashOut;
					break;
					
				case RLEStates.STATE_SYSTEM_RLE_SPLASH:
					systemFunction = RLE_Splash;
					break;
					
				case RLEStates.STATE_SYSTEM_RLE_SPLASH_OUT:
					systemFunction = RLE_SplashOut;
					break;
					
				case RLEStates.STATE_SYSTEM_TITLE:
					systemFunction = systemTitle;
					break;
					
				case RLEStates.STATE_SYSTEM_MENU:
					systemFunction = systemMenu;
					break;	
					
			    case RLEStates.STATE_SYSTEM_NEW_GAME:
					systemFunction = systemNewGame;
					break;	
					
				case RLEStates.STATE_SYSTEM_INSTRUCTIONS:
					systemFunction = systemInstructions;
					break;
					
				case RLEStates.STATE_SYSTEM_LEVEL_IN:
					systemFunction = systemLevelIn;
					break;
					
				case RLEStates.STATE_SYSTEM_NEW_LEVEL:
					systemFunction = systemNewLevel;
					break;
					
				case RLEStates.STATE_SYSTEM_LEVEL_OUT:
					systemFunction = systemLevelOut;
					break;
					
				case RLEStates.STATE_SYSTEM_GAME_PLAY:
					systemFunction = systemGamePlay;
					break
					
				case RLEStates.STATE_SYSTEM_GAME_OVER:
					systemFunction = systemGameOver;
					break;
				case RLEStates.STATE_SYSTEM_MENU_IN:
					systemFunction = systemMenuIn;
					break;	
					
				case RLEStates.STATE_SYSTEM_MENU_OUT:
					systemFunction = systemMenuOut;
					break;
					
				case RLEStates.STATE_SYSTEM_PAUSE_IN:
					systemFunction = systemPauseOut;
					break;	
					
				case RLEStates.STATE_SYSTEM_PAUSE:
					systemFunction = systemPauseOut;
					break;
					
				case RLEStates.STATE_SYSTEM_PAUSE_OUT:
					systemFunction = systemPauseOut;
					break;
					
				case RLEStates.STATE_SYSTEM_PRELOAD: 
					systemFunction = systemPreload;
					break;
					
				case RLEStates.STATE_SYSTEM_LOAD: 
					systemFunction = systemLoad;
					break;
					
				case RLEStates.STATE_SYSTEM_LOAD_FINISH: 
					systemFunction = systemLoadFinish;
					break;
					
				case RLEStates.STATE_SYSTEM_OPTIONS: 
					systemFunction = systemOptions;
					break;
				
			}
			systemFunction();
		}
		
		
		public function addTickTimer(id:String, timeToWait:int, loop:Boolean=false, manualDispose:Boolean=false):void {			
			vTimers.push( timerM.addTickTimer(id, timeToWait, this, loop, manualDispose) );
		}
		
		public function executeTimer(id:String):void 	{
			
		}
		
		public function getTimer(id:String):ITimer {
			i = vTimers.length -1;
			var tempTimer:RLETickTimer;
			for (i; i > -1; i--) {
				tempTimer = vTimers[i];
				if (id == tempTimer.sID) {
					return tempTimer;
				}
			}
			return null;
		}
		
		public function removeTimer(timer:ITimer):void {
			
		}
		
		public function getLevelData():IScore {
			return levelM.getCurrLevelData();
		}
		
		public function get worldHeight():int {
			return _worldHeight;
		}
		
		public function get worldWidth():int {
			return _worldWidth;
		}
		
		public function set worldHeight(num:int):void{
			_worldHeight = num;
		}
		
		public function set worldWidth(num:int):void {
			_worldWidth = num;
		}
		
		public function set frameRate(num:Number):void {
			_frameRate = num;
			stage.frameRate = _frameRate;
		}
		
		public function get frameRate():Number {
			return _frameRate;
		}
		
		public function get displayHeight():int {
			return stageHeight;
		}
		
		public function get displayWidth():int {
			return stageWidth;
		}
		
		public function get urlsAllowed():Array {
			return _urlsAllowed;
		}
		
		public function set urlsAllowed(value:Array):void {
			_urlsAllowed = value;
			sitelock();
		}
		
		public function advanceSystemState():void {
			switchSystemState(nextSystemState);
		}
		
		public function get bkgColor():uint {
			return _bkgColor;
		}
		
		public function set bkgColor(color:uint):void {
			_bkgColor = color;
		}
	}	
}